import Taro from "@tarojs/taro";
import { MemberResumeWorkExpRequest } from "@/apis/endpoint/model";
import { postMyAddoreditworkexp } from "@/apis/endpoint/my";
import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import GpVerticelLine from "@/components/GpVerticelLine";
import { pageMapper } from "@/constants/pageMap";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { dateFormat, dateUtil } from "@/utils/date";
import { navigate } from "@/utils/navigation";
import { DatetimePicker, Popup, Switch } from "@taroify/core";
import { Button, View } from "@tarojs/components";
import clsx from "clsx";
import { useEffect, useState } from "react";
import { useImmer } from "use-immer";
import { postQuickcompanies } from "@/apis/endpoint/home";

interface State {
  id?: number
  compName?: string
  position?: string
  content?: string
  achievement?: string
  department?: string
  isTransition?: boolean
  isHide?: boolean
}

interface WorkExp extends State {
  startAt?: string
  endAt?: string
}

export default function Index() {
  const [loading, setLoading] = useState(false)
  const [state, setState] = useImmer<State>({
    isHide: false,
    isTransition: false
  })
  const [openWork, setOpenWork] = useState(false)
  const [minWorkDate] = useState(new Date(2000, 0, 1))
  const [maxWorkDate] = useState(new Date())
  const [workAction, setWorkAction] = useState<"start"|"end"|"pending">("pending")
  const [workStartAt, setWorkStartAt] = useState<Date>()
  const [workEndAt, setWorkEndAt] = useState<Date>()
  const { eventChannel } = useNavigateEventChannel()
  useEffect(() => {
    if (eventChannel) {
      eventChannel.once("getWorkExp", (workExp: WorkExp) => {
        if (workExp) {
          const { startAt, endAt, ...s } = workExp
          if (startAt) setWorkStartAt(dateUtil(startAt).toDate())
          if (endAt) setWorkEndAt(dateUtil(endAt).toDate())
          setState({...state, ...s})
        }
      })
    }
  }, [])
  function triggerWorkAction(action: "start" | "end") {
    setWorkAction(action)
    setOpenWork(true)
  }
  function confirmWorkAction(date: Date) {
    workAction === "start" ? setWorkStartAt(date) : setWorkEndAt(date)
    setOpenWork(false)
    setWorkAction("pending")
  }
  function handleEditCompname() {
    navigate(pageMapper.fieldEdit.search, null, "navigateTo", {
      events: {
        receiveField({ label }: IOption<any>) {
          setState(draft => {
            draft.compName = label
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          maxContent: 40,
          navigationbarTitleText: "公司名称",
          placeholder: "请输入公司名称",
          searchAction(value) {
            return postQuickcompanies({
              top: 20,
              keywords: value
            }).send({ showLoading: false })
          },
          content: state.compName
        } as FieldEditStateSearch)
      },
    })
  }
  function handleEditPosition() {
    navigate(pageMapper.fieldEdit.simple, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.position = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          navigationbarTitleText: "职位名称",
          placeholder: "请输入职位名称",
          content: state.position,
          maxContent: 20
        } as FieldEditStateSimple)
      },
    })
  }
  function handleEditContent() {
    navigate(pageMapper.fieldEdit.multiline, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.content = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          content: state.content,
          description: "描述工作背景，负责的内容、克服的困难、取得的成果，便于HR了解您丰富的经验",
          filedName: "工作内容",
          placeholder: "1.负责领域\n2.负责工作\n3.具备业务能力",
        } as FieldEditState)
      },
    })
  }
  function handleEditAchievement() {
    navigate(pageMapper.fieldEdit.multiline, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.achievement = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          content: state.achievement,
          description: "展现完整、有吸引力的业绩，吸引更多HR关注",
          filedName: "工作业绩",
          placeholder: "1.取得的成绩\n2.实现的突破\n3.获得的表彰",
        } as FieldEditState)
      },
    })
  }
  function handleEditDepartment() {
    navigate(pageMapper.fieldEdit.simple, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.department = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          navigationbarTitleText: "所属部门",
          placeholder: "请输入部门名称",
          content: state.department,
          maxContent: 10
        } as FieldEditStateSimple)
      },
    })
  }
  async function handleSave() {
    if (!state.compName) {
      Taro.showToast({
        title: "请输入公司名称",
        icon: "none"
      })
      return
    }
    if (!workStartAt) {
      Taro.showToast({
        title: "请选择入职时间",
        icon: "none"
      })
      return
    }
    if (!workEndAt) {
      Taro.showToast({
        title: "请选择离职时间",
        icon: "none"
      })
      return
    }
    if (!state.position) {
      Taro.showToast({
        title: "请输入职位名称",
        icon: "none"
      })
      return
    }
    if (!state.content) {
      Taro.showToast({
        title: "请输入工作内容",
        icon: "none"
      })
      return
    }
    const params: MemberResumeWorkExpRequest = {
      companyName: state.compName,
      startTime: dateFormat(workStartAt, "short"),
      endTime: dateFormat(workEndAt, "short"),
      positionName: state.position,
      content: state.content,
      isInternship: state.isTransition!,
      isHideMe: state.isHide!,
      id: state.id,
      performance: state.achievement,
      departmentName: state.department
    }
    try {
      setLoading(true)
      await postMyAddoreditworkexp(params).send()
      Taro.showToast({
        title: (params.id ? "修改" : "新增") + "成功",
        icon: "success"
      })
      navigate()
    } catch (error) {
      setLoading(false)
    }
  }
  function renderActionPannels() {
    return (
      <View>
        { renderWorkRange() }
      </View>
    )
  }
  function renderWorkRange() {
    return (
      <Popup open={openWork} rounded placement="bottom" onClose={setOpenWork}>
        <Popup.Backdrop />
        <DatetimePicker
          type="year-month"
          min={minWorkDate}
          max={maxWorkDate}
          defaultValue={workAction === "start" ? workStartAt : workEndAt}
          key={workAction}
          onConfirm={confirmWorkAction}
        >
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button type="cancel">取消</DatetimePicker.Button>
            <DatetimePicker.Title>{workAction === "start" ? "入职时间" : "离职时间"}</DatetimePicker.Title>
            <DatetimePicker.Button type="confirm">确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>
    )
  }
  return (
    <GpContainer className="bg-white">
      <View className="px-[32px] box-border pt-[16px]">
        <View className="text-[48px] font-bold text-primary">工作经历</View>
        <View className="text-[28px] mt-[28px] text-primary">向HR展示你的工作能力</View>
      </View>
      <View className="px-[32px] pb-[48px]">
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">公司名称</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditCompname}>
            <View className={clsx("text-[32px] truncate", state.compName ? "text-primary font-bold" : "text-placeholder")}>
              {state.compName || "请输入公司名称"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">在职时间</View>
          <View className="flex flex-row justify-between items-center gap-[24px] mt-[32px]">
            <View onClick={() => triggerWorkAction('start')} className={clsx("text-[32px] flex-1", workStartAt ? "text-primary font-bold" : "text-placeholder")}>
              {workStartAt ? dateFormat(workStartAt, "YYYY/MM") : "入职时间"}
            </View>
            <GpVerticelLine width={20} height={2} color="#313337" />
            <View onClick={() => triggerWorkAction('end')} className={clsx("text-[32px] flex-1", workEndAt ? "text-primary font-bold" : "text-placeholder")}>
              {workEndAt ? dateFormat(workEndAt, "YYYY/MM") : "离职时间"}
            </View>
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">职位名称</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditPosition}>
            <View className={clsx("text-[32px] truncate", state.position ? "text-primary font-bold" : "text-placeholder")}>
              {state.position || "请输入职位名称"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">工作内容</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditContent}>
            <View className={clsx("text-[32px] truncate", state.content ? "text-primary font-bold" : "text-placeholder")}>
              {state.content || "请输入工作内容"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
      </View>
      <View className="w-full h-[24px] bg-[#F4F6FC]"></View>
      <View className="px-[32px] py-[48px]">
        <View className="text-secondary text-[28px]">以下为选填项</View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">工作业绩</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditAchievement}>
            <View className={clsx("text-[32px] truncate", state.achievement ? "text-primary font-bold" : "text-placeholder")}>
              {state.achievement || "请输入工作业绩（填选）"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">所属部门</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditDepartment}>
            <View className={clsx("text-[32px] truncate", state.department ? "text-primary font-bold" : "text-placeholder")}>
              {state.department || "请输入所属部门（填选）"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
      </View>
      <View className="w-full h-[24px] bg-[#F4F6FC]"></View>
      <View className="px-[32px] box-border pb-[32px]">
        <View className="border-b-2 border-solid border-b-[#EEEEEE] py-[46px]">
          <View className="flex flex-row justify-between items-center">
            <View className="text-[32px] text-primary">
              本段经历是实习经历
            </View>
            <Switch checked={state.isTransition} onChange={value => setState(draft => {draft.isTransition = value})} size={20} />
          </View>
        </View>
        <View className="border-b-2 border-solid border-b-[#EEEEEE] py-[46px]">
          <View className="flex flex-row justify-between items-center">
            <View className="text-[32px] text-primary">
              对这家公司隐藏我的信息
            </View>
            <Switch checked={state.isHide} onChange={value => setState(draft => {draft.isHide = value})} size={20} />
          </View>
          <View className="mt-[20px] text-[24px] text-placeholder">
            隐藏后，你和当前公司的 BOSS ，都不会被相互推荐，你的查看行为也不会告知对方，你将不会收到对方的任何消息。
          </View>
          <Button className="h-[80px] mt-[80px] rounded-[64px] bg-theme text-white flex flex-row justify-center items-center text-[32px]" loading={loading} onClick={handleSave}>
            保存
          </Button>
        </View>
      </View>
      { renderActionPannels() }
    </GpContainer>
  )
}
